import React from 'react';
import { connect } from 'react-redux';

import { Layout, Menu, Icon, Button } from 'antd';

import { Route, Switch } from 'react-router-dom';
import Login from './pages/login';
import Home from './pages/home';
import Team from './pages/team';
import Goods from './pages/goods';

import axios from './common/axios';


const { Sider, Content, Footer } = Layout;




export default connect((state, props) => {
  return { ...props, token: state.token, access: state.access }
}, dispatch => ({
  clear_token: () => dispatch({ type: 'clear_token' })
}))(props => {
  const { token, history, clear_token, access } = props;

  const menus = [
    { title: '首页', icon: 'home', path: '/', exact: true, component: Home },
    { title: '团队管理', icon: 'team', path: '/team', component: Team },

    ...(access.goods_add || access.goods_view || access.goods_del || access.goods_mod) ?
      [{ title: '商品管理', icon: 'shopping', path: '/goods', component: Goods }] : []
  ];


  const logout = async ev => {
    await axios('/logout');

    clear_token();
  };

  // const [menuKey, setMenuKey]=useState(menus[0].path);

  return (
    <div>
      {token ? (
        <Layout style={{ minHeight: '100vh' }}>
          <Sider collapsible>
            <Menu
              theme="dark"
              mode="inline"
              defaultSelectedKeys={[props.location.pathname]}
              onClick={ev => history.push(ev.key)}
            >
              {menus.map(menu => (
                <Menu.Item key={menu.path}>
                  <Icon type={menu.icon} />
                  <span>{menu.title}</span>
                </Menu.Item>
              ))}
            </Menu>
          </Sider>
          <Layout>
            <Content>
              <Button onClick={logout}>退出登录</Button>
              <Switch>
                {menus.map(menu => (
                  <Route
                    key={menu.path}
                    path={menu.path}
                    exact={menu.exact}
                    component={menu.component}
                  />
                ))}
              </Switch>
            </Content>
            <Footer style={{ textAlign: 'center' }}>
              xxx公司版权所有
            </Footer>
          </Layout>
        </Layout>
      ) : (
          <Login />
        )}

    </div>
  );
});
